package hk.ust.cse.comp3111.studentSchedule;


import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.ContentUris;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.provider.CalendarContract;
import android.text.format.DateFormat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class ViewCalendar_week extends Fragment {
	
	View rootView;
	TextView sundayDateTextView;
	TextView mondayDateTextView;
	TextView tuesdayDateTextView;
	TextView wednesdayDateTextView;
	TextView thursdayDateTextView;
	TextView fridayDateTextView;
	TextView saturdayDateTextView;
	
	int testForCalculation;
	
	static final long oneD=86400000L;
	
	@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
 
        View rootView = inflater.inflate(R.layout.calendar_weekly, container, false);
        
        
        //add blue day marker
        /*View pl = rootView.findViewById(R.id.thursdayHeaderRelativeLayout);
        View Paper = new View(pl.getContext());
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.FILL_PARENT,2);
        params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
        Paper.setLayoutParams(params);
        Paper.setBackgroundColor(Color.BLUE);
        ((RelativeLayout)pl).addView(Paper);*/
        
        
      //demo add event Title TitleABC at Friday 14:00
        /*View pl = rootView.findViewById(R.id.fridayRelativeLayout);
        View Paper = new View(pl.getContext());
        TextView tv=new TextView(this.getActivity());
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, 60);
        params.setMargins(0, 840, 6, 0); //1380-"*60"=
        tv.setLayoutParams(params);
        tv.setText("TitleABC");
        ((RelativeLayout)pl).addView(tv);
        
        
        for(int i=0;i<10;i++){
        	View p2 = rootView.findViewById(R.id.fridayRelativeLayout);
            TextView tv1=new TextView(this.getActivity());
            RelativeLayout.LayoutParams params1 = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, 60);
            params1.setMargins(0, 2*i*90, 6, 0); //1380-"*60"=
            tv1.setLayoutParams(params1);
            tv1.setText("Title" + 2*i);
            ((RelativeLayout)p2).addView(tv1);
        }*/
        
        Cursor cur = null;  
        long adjust=0-getWeekDay();
        Calendar cal1 = Calendar.getInstance();
        
        cal1.clear(Calendar.HOUR_OF_DAY);
        cal1.clear(Calendar.AM_PM);
        cal1.clear(Calendar.MINUTE);
        cal1.clear(Calendar.SECOND);
        cal1.clear(Calendar.MILLISECOND);
        long timeNow=cal1.getTimeInMillis();
        long timeTemp=0;
        
        
        View p00 = rootView.findViewById(R.id.sundayRelativeLayout);
		View p01 = rootView.findViewById(R.id.mondayRelativeLayout);
		View p02 = rootView.findViewById(R.id.tuesdayRelativeLayout);
		View p03 = rootView.findViewById(R.id.wednesdayRelativeLayout);
		View p04 = rootView.findViewById(R.id.thursdayRelativeLayout);
		View p05 = rootView.findViewById(R.id.fridayRelativeLayout);
		View p06 = rootView.findViewById(R.id.saturdayRelativeLayout);
		
		List<View> viewList = new ArrayList<View>();
		viewList.add(p00);
		viewList.add(p01);
		viewList.add(p02);
		viewList.add(p03);
		viewList.add(p04);
		viewList.add(p05);
		viewList.add(p06);
		
		String columns[] = new String[] { "calendar_id", "title", "description", "event_id", "startDay", "startMinute", "endMinute"};
		
		
		for(int l =0 ; l<7 ; l++){
			Uri.Builder eventsUriBuilder1 = CalendarContract.Instances.CONTENT_URI.buildUpon();
			ContentUris.appendId(eventsUriBuilder1, timeNow+(adjust+l)*oneD);
			ContentUris.appendId(eventsUriBuilder1, timeNow+(adjust+l)*oneD+oneD-1000L);
			Uri eventsUri = eventsUriBuilder1.build();   
			cur = this.getActivity().getContentResolver().query(eventsUri, columns, null, null, CalendarContract.Instances.DTSTART + " ASC");
			
			if (cur.moveToFirst()) {
			Toast.makeText(this.getActivity().getApplicationContext(), cur.getString(3), Toast.LENGTH_LONG).show();
			}
			if (cur.moveToFirst()) {
	            do {
	            	long eventIDs=Long.parseLong(cur.getString(3));
	            	//do
	            	//View p4 = rootView.findViewById(R.id.fridayRelativeLayout);
	                View Paper4 = new View(viewList.get(l).getContext());
	                TextView tv4=new TextView(this.getActivity());
	                int h=(int) ((Integer.parseInt(cur.getString(6))-Integer.parseInt(cur.getString(5)))*1.5);
	                RelativeLayout.LayoutParams params4 = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, h);
	                //int k=(int) (Long.parseLong(cur.getString(5))*1.5);
	                params4.setMargins(0, (int) (Long.parseLong(cur.getString(5))*1.5), 6, 0); //1380-"*60"=
	                tv4.setLayoutParams(params4);
	                tv4.setText(cur.getString(1).toString());
	                tv4.setBackgroundColor(Color.MAGENTA);
	                ((RelativeLayout)viewList.get(l)).addView(tv4);
	                
	                String temp=tv4.getText().toString();
	                MyListener listener = new MyListener();
	                listener.setName(temp);
	                listener.setValue(eventIDs);
	                listener.setTime(timeNow+(adjust+l)*oneD, timeNow+(adjust+l)*oneD+oneD-1000L);
	                tv4.setOnClickListener(listener);
	                
	                
	                //Toast.makeText(this.getActivity().getApplicationContext(), cur.getString(1), Toast.LENGTH_LONG).show();
	            } while (cur.moveToNext());
	        }
		}
        
        
        /*long j=4;
        timeTemp=timeNow+(adjust+j)*oneD;
		
        Uri.Builder eventsUriBuilder1 = CalendarContract.Instances.CONTENT_URI.buildUpon();
		
		ContentUris.appendId(eventsUriBuilder1, timeTemp);
		ContentUris.appendId(eventsUriBuilder1, timeTemp+oneD-1000L);
		Uri eventsUri = eventsUriBuilder1.build();     
		
		
		cur = this.getActivity().getContentResolver().query(eventsUri, columns, null, null, CalendarContract.Instances.DTSTART + " ASC");
		
		
		
		
		if (cur.moveToFirst()) {
            do {
            	//do
            	View p4 = rootView.findViewById(R.id.fridayRelativeLayout);
                View Paper4 = new View(p4.getContext());
                TextView tv4=new TextView(this.getActivity());
                RelativeLayout.LayoutParams params4 = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, 60);
                int k=(int) (Long.parseLong(cur.getString(5))*1.5);
                params4.setMargins(0, k, 6, 0); //1380-"*60"=
                tv4.setLayoutParams(params4);
                tv4.setText(cur.getString(1).toString());
                ((RelativeLayout)p4).addView(tv4);
                Toast.makeText(this.getActivity().getApplicationContext(), cur.getString(1), Toast.LENGTH_LONG).show();
            } while (cur.moveToNext());
        }*/
		
		
        
        
        View p3=null;
        switch(getWeekDay()){
        case 0:
        	p3=rootView.findViewById(R.id.sundayHeaderRelativeLayout);
        	break;
        case 1:
        	p3=rootView.findViewById(R.id.mondayHeaderRelativeLayout);
        	break;
        case 2:
        	p3=rootView.findViewById(R.id.tuesdayHeaderRelativeLayout);
        	break;
        case 3:
        	p3=rootView.findViewById(R.id.wednesdayHeaderRelativeLayout);
        	break;
        case 4:
        	p3=rootView.findViewById(R.id.thursdayHeaderRelativeLayout);
        	break;
        case 5:
        	p3=rootView.findViewById(R.id.fridayHeaderRelativeLayout);
        	break;
        case 6:
        	p3=rootView.findViewById(R.id.saturdayHeaderRelativeLayout);
        	break;
        }

        View Paper3 = new View(p3.getContext());
        RelativeLayout.LayoutParams params3 = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,2);
        params3.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
        Paper3.setLayoutParams(params3);
        Paper3.setBackgroundColor(Color.BLUE);
        ((RelativeLayout)p3).addView(Paper3);
   
	
        
        
        return rootView;
    }
	
	@Override
	public void onStart() {
		super.onStart();
		
		sundayDateTextView=(TextView)this.getView().findViewById(R.id.sundayDateTextView);
		mondayDateTextView=(TextView)this.getView().findViewById(R.id.mondayDateTextView);
		tuesdayDateTextView=(TextView)this.getView().findViewById(R.id.tuesdayDateTextView);
		wednesdayDateTextView=(TextView)this.getView().findViewById(R.id.wednesdayDateTextView);
		thursdayDateTextView=(TextView)this.getView().findViewById(R.id.thursdayDateTextView);
		fridayDateTextView=(TextView)this.getView().findViewById(R.id.fridayDateTextView);
		saturdayDateTextView=(TextView)this.getView().findViewById(R.id.saturdayDateTextView);
		
		List<TextView> test = new ArrayList<TextView>();
		test.add(sundayDateTextView);
		test.add(mondayDateTextView);
		test.add(tuesdayDateTextView);
		test.add(wednesdayDateTextView);
		test.add(thursdayDateTextView);
		test.add(fridayDateTextView);
		test.add(saturdayDateTextView);
		
		
		//this.getActivity().getActionBar().setTitle("DLLM");
		
		SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd");
		SimpleDateFormat dateFormatGetWeekDay = new SimpleDateFormat("E");
		
		 Calendar cal = Calendar.getInstance();
	        String today=dateFormat.format(cal.getTime()).toString();
	        int weekDay=0;
        //int weekDay=Integer.parseInt(dateFormatGetWeekDay.format(cal.getTime()));
        
        String weekDays = dateFormatGetWeekDay.format(cal.getTime());
        if(weekDays.equals("Mon")) weekDay=1;
        else if (weekDays.equals("Tue")) weekDay=2;
        else if (weekDays.equals("Wed")) weekDay=3;
        else if (weekDays.equals("Thu")) weekDay=4;
        else if (weekDays.equals("Fri")) weekDay=5;
        else if (weekDays.equals("Sat")) weekDay=6;
        else if (weekDays.equals("Sun")) weekDay=0;
        

	        long timeTemp=cal.getTimeInMillis();;
	        
	        long adjustment=0L-weekDay;
	        String temp;
	        
	        for(int i=0;i<7;i++){
	        	cal.setTimeInMillis(timeTemp+(adjustment+i)*oneD);
	        	temp=dateFormat.format(cal.getTime()).toString();
	        	test.get(i).setText(temp);
	        	
	        }
	        
	
	}
	
	
	
	int getWeekDay(){
		SimpleDateFormat dateFormatGetWeekDay = new SimpleDateFormat("E");
		 Calendar cal = Calendar.getInstance();
		 String weekDays = dateFormatGetWeekDay.format(cal.getTime());
		 if(weekDays.equals("Mon"))  return 1;
	        else if (weekDays.equals("Tue")) return 2;
	        else if (weekDays.equals("Wed")) return 3;
	        else if (weekDays.equals("Thu")) return 4;
	        else if (weekDays.equals("Fri")) return 5;
	        else if (weekDays.equals("Sat")) return 6;
	        else if (weekDays.equals("Sun")) return 0;
		return 0;
	}
	
	private void push(String eventID,String start, String end) {
    	Bundle save=new Bundle();
		save.putString("eventID",eventID);
		save.putString("start", start);
		save.putString("end", end);
		Fragment fragment = new ViewCalendar_singleItem();
		fragment.setArguments(save); 
		FragmentManager fragmentManager = getFragmentManager();
		fragmentManager.beginTransaction()
				.replace(R.id.frame_container, fragment).commit();
		
	}
	
	class MyListener implements OnClickListener
	{ 
	    String nulls;
	    long eventID;
	    long start;
	    long end;

	    void setName(String newName)
	    {
	    	nulls = newName;
	    }

	    void setValue(long newValue)
	    {
	    	eventID = newValue;
	    }
	    
	    void setTime(long a, long b)
	    {
	        start =a;
	        end =b;
	    }
	    
	    
	    public void onClick(View v) 
	    {
	    	Activity activity = getActivity();
	        // Use the data for some unknown purpose
	    	//Toast.makeText(activity,"you clicked ID "+value,Toast.LENGTH_LONG).show();
	    	push(String.valueOf(eventID),String.valueOf(start),String.valueOf(end));
	    	//Toast.makeText(activity,"you clicked ID "+eventID,Toast.LENGTH_LONG).show();
	    	//Toast.makeText(activity,"time "+start,Toast.LENGTH_LONG).show();
	    	//Toast.makeText(activity,"time "+end,Toast.LENGTH_LONG).show();
	    }


	}
	
	
	

}
